let ErrorUtils = require('../utils/error/ErrorUtils');
let {User} = require('../models');
let lodash = require('lodash');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');
let rp = require('request-promise');
let wechat = require('./wechat');
let redis = require('../redis');
let user = require('./user');
let config = require('../config');

class LoginService {
    static async index(content) {
        return content;
    }

    static checkValiData(data) {
        let schema = Joi.object({
            username: Joi.string().min(3).max(16).required(),
            password: Joi.string().min(6).max(16).required()
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    static checkLoginDate(data) {
        let schema = Joi.object({
            code: Joi.string().required(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     *  用户登录
     * @param data
     * @returns {Promise<void>}
     */
    static async login(data) {
        infoLogger.info('>>>>>>小程序登录开始,请求参数为:', data);
        await LoginService.checkLoginDate(data);
        let result = await wechat.getSessionKey(data.code);
        infoLogger.info(">>>>>result:",result);
        if (result.errcode) {
            ErrorUtils.throwApiError(ErrorUtils.WECHAT_CODE_ERROR);
        }
        //存储用户信息
        let userInfo = await redis.hgetall(`wechat:user:openid:${result.openid}`);
        let response;
        if (userInfo && JSON.stringify(userInfo) != '{}') {
            response = lodash.pick(userInfo, [
                '_id', 'avatarUrl', 'gender', 'nickName', 'city', 'province', 'openId', 'unionId',
            ]);
            await redis.hmset(`${config.auth.wechatLoginPrefix}${result.openid}`, 'sessionKey', result.session_key);
            await redis.expire(`${config.auth.wechatLoginPrefix}${result.openid}`, config.auth.wechatTtl);
            response.isNew = false;
        } else {
            //读取mongo user 数据
            let resultLocal = await user.saveUserInfo(result);
            // 将用户信息存入redis
            response = lodash.pick(resultLocal.userDoc.toJSON(), [
                '_id', 'avatarUrl', 'gender', 'nickName', 'city', 'province', 'openId', 'unionId',
            ]);
            response.isNew = resultLocal.isNew;
            response.sessionKey = result.session_key;
            await redis.hmset(`${config.auth.wechatLoginPrefix}${result.openid}`, response);
            await redis.expire(`${config.auth.wechatLoginPrefix}${result.openid}`, config.auth.wechatTtl);
        }
        return response;
    }
}

module.exports = LoginService;
